import siteinfo from "@/siteinfo.js"
import store from '@/store/index.js'
var core = {
	loading : false,
	inited:false,
	debug:false,
	inwechat:false,
	inithandel:null,
	jweixin:null,
	system:{
		name:"",
		closesystem:0,
		siteroot:"",
		client:{}
	},
	/**
	 * 后端传输的token 用作判断用户有没有登陆
	 */
	userinfo:{uid:0,token:''},
	caches:{upgradetip:''},
	agentid:0,
	platform:'',
	device:'android',
	version:'1.2.10',
	apitoken:'',
	init:function(userstate=''){
		this.platform = this.initplatform();
		this.apitoken = siteinfo.token;
		if((userstate!='' && this.userinfo.uid==0) || this.debug){
			this.initsys(userstate);
		}else{
			var that = this;
			this.cacheread('_swa_education_system_session_',function(res){
				// alert(12)
				// if(res.data.member.uid>0){
				// 	that.login(res.data.member,false);
				// }
				if(typeof(res.data.caches)!='undefined'){
					that.caches = res.data.caches;
				}
				that.initpage(res.data);
			},function(e){
				that.initsys(userstate);
			});
		}
	},
	initsys:function(state=''){
		let postdata = {v:this.version};
		if(state!='') postdata.state = state;
		var that = this;
		this.get('appconfig',function(res){
			if(res.member.uid==0){
				res.member = that.userinfo;
			}else if(that.userinfo.uid!=res.member.uid){
				if(that.userinfo.uid>0){
					that.logout(false);
				}
				that.login(res.member,false);
			}
			//执行系统设置变化需要初始化的信息
			that.initpage(res);
			//读取系统设置并保存到本地
			res.caches = that.caches;
			res.caches.upgradetip = res.system.client.version;
			that.cacheset('_swa_education_system_session_',res);
		},postdata);
	},
	initpage : function(data){
		this.system = data.system;
		this.inwechat = data.system.inwechat;
		if(data.system.closesystem==1){
			let platform = this.platform;
			return this.confirm(data.system.closetext,'系统维护通知',function(){
				if(platform=='app'){
					return plus.runtime.quit();
				}
			},{showCancel:false});
		}
		this.inited = true;
		if(typeof(this.inithandel)=='function'){
			this.inithandel();
		}
		if(typeof(data.system.client)!='undefined'){
			if(data.system.client.upgrade && data.system.client.version!=this.cache.upgradetip){
				this.confirm('新版本（V'+data.system.client.version+'），更多好玩优质内容邀请您体验','发现新版本',function(){
					core.upgrade(data.system.client.upgradeurl);
				},{
					confirmText:'立即体验',
					cancelText:'不再提醒'
				});
			}
		}
	},
	inituser : function(family){
		if(this.userinfo.uid==0) return false;
		//初始化用户信息
	},
	initshare : function(title,url,cover='',summary=''){
		let ShareObject = {
			title : title,
			url: url,
			cover : cover,
			summary : summary,
			providers : 4,
			provider : {
				"weixin":{
					switch:false,
					title:'微信好友',
					icon:'auth_weixin.png'
				},
				"wxtimeline":{
					switch:false,
					title:'朋友圈',
					icon:'share_wxtimeline.png'
				},
				"qq":{
					switch:false,
					title:'QQ',
					icon:'auth_qqconnect.png'
				},
				"sinaweibo":{
					switch:false,
					title:'微博',
					icon:'auth_sina.png'
				}
			}
		};
		if(this.platform!='h5'){
			uni.getProvider({
			    service: 'share',
			    success: function (res) {
					ShareObject.providers = res.provider.length;
					for(let i in res.provider){
						ShareObject.provider[res.provider[i]].switch = true;
						if(res.provider[i]=='weixin'){
							ShareObject.provider.wxtimeline.switch = true;
							ShareObject.providers += 1;
						}
					}
			    }
			});
		}else if(this.inwechat){
			let sharedata = {title:title,desc:summary?summary:title,link:ShareObject.url,imgUrl:cover};
			this.initjwx(function(jweixin){
				jweixin.updateAppMessageShareData(sharedata);
				jweixin.updateTimelineShareData(sharedata);
				jweixin.onMenuShareWeibo(sharedata);
			});
		}
		return ShareObject;
	},
	initjwx:function(callback){
		if(!this.inwechat) return false;
		if(this.jweixin==null){
			let jwx = require('jweixin-module');
			let url = location.href.split('#')[0];
			var that = this;
			this.get('getjssdk',function(res){
				res.jsApiList = ['checkJsApi','scanQRCode','updateTimelineShareData','updateAppMessageShareData'];
				res.debug = core.debug;
				jwx.config(res);
				jwx.ready(function(){
					that.jweixin = jwx;
					if(typeof(callback)=='function'){
						return callback(jwx);
					}
				});
				jwx.error(function(res){
					that.jweixin = null;
					if(core.debug) core.toast(res.msg);
					console.log(res);
				});
			},{url:url});
		}else if(typeof(callback)=='function'){
			return callback(this.jweixin);
		}
	},
	/**
	 * 登录成功后调用
	 */
	login : function(data,cache=true){
		if(!data.cloudLogin.uid) return this.toast('Unknown UID');
		this.userinfo=data.cloudLogin;
		this.userinfo.token=data.token;
		console.log(this.userinfo)
		store.commit('login',data);
		this.inituser();
		if(cache){
			//登录成功后将会员信息更新到本地缓存
			let system_session = {system:this.system,member:this.userinfo,caches:this.caches};
			//console.log(system_session.userinfo)'_swa_education_system1111_session_',
			this.initpage(system_session);
			
		}
		console.log('用户'+data.cloudLogin.nickname+'登录成功！');
		return true;
	},
	logout : function(cache=true){
		this.get('auth/logout',function(){});
		this.userinfo = {uid:0};
		if(cache){
			//退出成功后将会员信息更新到本地缓存
			let system_session = {system:this.system,member:this.userinfo,caches:this.caches};
			this.cacheset('_swa_education_system_session_',system_session);
		}
		store.commit('logout');
		return true;
	},
	scan : function(callback){
		if(this.platform=='h5'){
			if(this.inwechat){
				return this.initjwx(function(jwx){
					jwx.scanQRCode({
						needResult:0,
						scanType: ["qrCode","barCode"]
					});
				});
			}
			return this.toast('请在APP上使用该功能');
		}
		uni.scanCode({
		    success: function (res) {
		        if(typeof(callback)=='function'){
		        	return callback(res);
		        }else{
		        	if(res.result.indexOf('http')==0 || res.result.indexOf('/pages/')>-1){
		        		core.navito(res.result);
		        	}else{
		        		core.confirm(res.result,'扫描结果',function(){
		        			core.copy(res.result);
		        		},{confirmText:'复制到剪切板'});
		        	}
		        }
		    },
			fail:function(e){
				console.log('扫码失败：');
				console.log(e);
			}
		});
	},
	copy:function(text){
		if(this.platform=='h5') return this.toast('请在APP上使用此功能');
		if(!text) return this.toast('复制的内容为空');
		return uni.setClipboardData({
			data: text,
			success: function () {
				core.toast('已复制到剪切板','','success');
			},
			fail:function(e){
				console.log(e);
				core.toast('复制失败');
			}
		});
	},
	back:function(){
		if(this.inwechat) this.jweixin = null;
		let pages = getCurrentPages();
		if(pages.length>1){
			uni.navigateBack();
		}else{
			uni.reLaunch({
				url:'/pages/index/index'
			})
		}
	},
	cacheread : function(key,callback,fail){
		var getstorage = {key:key};
		if(typeof(callback)=='function'){
			getstorage.success = callback;
		}
		if(typeof(fail)=='function'){
			getstorage.fail = fail;
		}
		return uni.getStorage(getstorage);
	},
	cacheset : function(key,data){
		uni.setStorage({key:key,data:data,fail:function(e){
			console.log('写入缓存失败：');
			console.log(e);
		},success:function(){
			console.log('写入缓存成功！');
		}});
	},
	 confirm:function(msg,title,callback,options={},Cancel){
		options = options || {};
		options.content = msg;
		if(title) options.title = title;
		if(typeof(options.success)=='undefined' && typeof(callback)=='function'){
			options.success = function(res){
				if(res.confirm){
					callback();
				}else if(res.cancel && typeof(Cancel)=='function'){
					Cancel();
				}
			};
		}
		return uni.showModal(options);
	},
	get : function (u,c,d,t,l){
		return this.request(u,'GET',d,t,c,l);
	},
	post : function (u,c,d,t,l) {
		return this.request(u,'POST',d,t,c,l);
	},
	url : function(route="",action='api'){
		route = route.replace('/','.');
		if (route.indexOf('http')==0 || route.indexOf('/index.php')>-1) return route;
		var baseurl = siteinfo.siteroot + '?i='+siteinfo.uniacid+'&c=entry&m=swa_education&do='+action+'&unifrom='+this.platform;
		if(action=='api'){
			baseurl = baseurl.replace('app/index.php','app/swaapi.php');
		}else if(this.platform=='h5' && baseurl.indexOf('http')!==0){
			baseurl = this.system.siteroot + baseurl;
		}
		if (route=='' || !route) return baseurl;
		console.log("url地址")
		console.log(baseurl + '&r='+route)
		return baseurl + '&r='+route;
	},
	/**
	 * 拼接url地址
	 */
	page : function(url='',data = {}){
		if(url=='') url = 'index/index';
		if(url=='#' || url.indexOf('javascript:')==0) return '';
		// ***#/pages/***
		if(url.indexOf('#/pages/')>0){
			let urls = url.split('#/pages/');
			url = urls[1];
		}else{
			// *** /#/pages/ ***
			url = url.replace('#/pages/','',url);			
		}
		if(url.indexOf('http')==0){
			return '/pages/index/web?url=' + encodeURIComponent(url);
		}
		if(url.indexOf('/pages/')!=0) url = '/pages/' + url;
		for (let key in data) {
			//例如 act:login												'lector/detail',{uid:item.id}
			//       ？是传输数据 没有？为-1 ？& key=value act:login #/pages/auth/index?act=login
			url += (url.indexOf('?') == -1 ? '?' : '&') + key + '=' + data[key]
		}
		return url;
	},
	upload:function(file,callback,type="image",apiname="util/upload"){
		var formdata = {"submit":1,"authkey":this.userinfo.token,"unifrom":this.platform,"type":type,"uploadfile":"file"};
		if(!this.loading){
			this.loading = true;
			uni.showLoading({
				mask:true,
				title:'上传中...'
			});
		}
		var that = this;
		console.log(file)
	    uni.uploadFile({
			url: "http://localhost:8070/home/uploadImage",
			filePath: file,
			name: 'file',
			formData: formdata,
			success: function(uploadres){
				var res = JSON.parse(uploadres.data);
				// if(res.type!='success') return that.report(res);
				if(typeof(callback)=='function'){
					return callback(res);
				}
			},
			fail:function(e){
				that.toast('上传失败');
				console.log('文件上传失败：');
				console.log(e);
			},
			complete:function(){
				if(that.loading){
					uni.hideLoading();
					that.loading = false;
				}
			}
		});
	},
	evaljs:function(scripttext){
		let scripts = scripttext.split(":");
		let script = "core."+scripts[1]+"("+(typeof(scripts[2])!='undefined'?"'"+scripts[2]+"'":"")+")";
		eval(script);
	},
	navito : function(page,data={},type = 0){//'lector/detail',{uid:item.id}
		if(page.indexOf('core:')==0) return this.evaljs(page);
		var url = this.page(page,data);
		if(url=='') return false;
		if(this.inwechat) this.jweixin = null;
		switch (type) {
			case 0:
			/**
			 * 跳转到本页面的url地址下
			 */
				uni.navigateTo({
					url,
					fail: console.log
				})
				break;
			case 1:
				uni.redirectTo({
					url,
					fail: console.log
				})
				break;
			case 2:
				uni.reLaunch({
					url,
					fail: console.log
				})
				break;
			case 3:
				uni.navigateBack({
					delta: url,
					fail: console.log
				})
				break;
			case 4:
				uni.switchTab({
					url: url,
					fail: console.log
				})
				break;
		}
	},
	request : function (u,m,d,t,c,l) {
		var url = this.url(u);
		var method = m ? m : 'GET';
		var data = d ? d : {};
		var datatype = t ? t : 'json';
		data.inajax = 1;
		if (method=='POST'){
			data.submit = 1;
		}
		console.log("userinfo.uid")
		console.log(this.userinfo.uid)
		if(this.userinfo.uid>0){
			data.authkey = this.userinfo.token;
		}
		console.log(data.authkey)
		if (l && !this.loading){
			this.loading = true;
			uni.showLoading({
				mask:true,
				title:'加载中'
			});
		}
		var callback = typeof(c)=='function' ? c : false;
		var hreq = this;
		return uni.request({
			url:url,
			method:method,
			dataType:datatype,
			data:data,
			success:function(res){
				if (typeof(callback)=='function'){
					return callback(res.data);
				}
				hreq.report(res.data);
			},
			fail:function(e){
				uni.showToast({
					title:'网络链接失败',
					icon:'none'
				})
				console.log(e);
			},
			complete:function(res){
				if(hreq.loading){
					hreq.loading = false;
					uni.hideLoading();
				}
			}
		});
	},
	report : function(res, initpage = false){
		if(res===null) res = {message:"敬请期待",redirect:'back',type:"error"};
		if(typeof(res)!='object' && this.isJsonString(res)){
			res = JSON.parse(res);
		}
		if (typeof(res)!='object') return false;
		if(res.redirect=='' && initpage){
			res.redirect = 'back';
		}
		if(typeof(res.url)!='undefined'){
			var act = typeof(res.act)=='undefined' ? 'undefined' : res.act;
			if (act=='redirect'){
				this.navito(res.url, 1);
			}
		}
		if(typeof(res.message)!='undefined'){
			this.toast(res.message,res.redirect,res.type);
		}
	},
	/**输出信息
	 * @param {Object} m
	 * @param {Object} u
	 * @param {Object} t
	 */
	toast : function(m,u,t){
		var toastinfo = {title:m,duration:1500};
		if(this.loading){
			uni.hideLoading();
			this.loading = false;
		}
		var that = this;
		if(u){
			toastinfo.complete = function(){
				setTimeout(function(){
					if(u=='back'){
						that.back();
					}else if(u=='home'){
						that.navito('index/index', {}, 2);
					}else if(u=='login'){
						that.navito('auth/index', {act:'login'}, 1);
					}else{
						that.navito(u,{},1);
					}
				},800);
			}
		}
		toastinfo.icon = (t=='success' || t=='loading') ? t : 'none';
		uni.showToast(toastinfo);
	},
	upgrade:function(url){
		if(this.platform!='app') return this.toast('该功能仅限APP内使用');
		if(this.device=='android' && url.indexOf('.apk')>-1){
			this.loading = true;
			uni.showLoading({
				mask:true,
				title:'正在下载安装包...'
			});
			uni.downloadFile({
			    url: url,
			    success: (res) => {
			        //console.log(res);
					uni.saveFile({
						tempFilePath:res.tempFilePath,
						success:function(res){
							plus.runtime.install(res.savedFilePath);
						},
						fail:function(e){
							core.toast('文件保存失败！');
							console.log(e);
						}
					})
			    },
				fail:function(e){
					core.toast('安装包下载失败');
					console.log(e);
				},
				complete() {
					core.loading = false;
					uni.hideLoading();
				}
			});
		}else{
			this.navito(url,{},0);
		}
	},
	launchapp(urlschemes,route='index/index'){
		//其它客户端唤醒APP，仅支持H5
		if(!urlschemes) return false;
		if(this.platform=='h5'){
			let appurl = urlschemes+'://'+route;
			if(document.getElementById('AppUrlSchemes')){
				document.getElementById('AppUrlSchemes').src = appurl;
			}else{
				let div = document.createElement("div");
				div.setAttribute("style", "display: none;visibility: hidden; width: 0; height: 0; overflow: hidden;");
				div.innerHTML = '<iframe id="AppUrlSchemes" src="'+appurl+'" frameborder="0" width="0" height="0"></iframe></div>';
				document.body.appendChild(div);
			}
		}
		return true;
	},
	isJsonString : function(str){
		try {
			if(typeof(JSON.parse(str)) == "object") {
				return true;
			}
		} catch(e) {
		}
		return false;
	},
	initplatform(){
		//#ifdef H5
		return 'h5';
		//#endif
		//#ifdef APP-PLUS || APP-PLUS-NVUE
		return 'app';
		//#endif
		//#ifdef MP-WEIXIN
		return 'wxapp';
		//#endif
		//#ifdef MP-ALIPAY
		return 'aliapp';
		//#endif
		//#ifdef MP-BAIDU
		return 'bdapp';
		//#endif
		//#ifdef MP-TOUTIAO
		return 'ttapp';
		//#endif
		//#ifdef MP-QQ
		return 'qqapp';
		//#endif
		//#ifdef MP-360
		return 'qhapp';
		//#endif
	}
}
module.exports = core;